package m.jclecai.com.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import m.jclecai.com.R;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        findViewById(R.id.btn_click).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                doRxJava();

            }
        });
    }

    /**
     * 这里我们要做的一个操作就是实现RxJava里面的背压的实现；
     */
    private void doRxJava() {

        Observable.range(1, 1000)
                .flatMap(new Func1<Integer, Observable<Integer>>() {
                    @Override
                    public Observable<Integer> call(Integer integer) {
                        try {
                            Thread.sleep(Math.max(2000 - integer * 100, 0));

                            if (integer == 20) {
                                throw new RuntimeException();
                            }

                        } catch (Exception e) {
                           return Observable.just(-1);
                        }
                        return Observable.just(integer);
                    }
                })
                .observeOn(Schedulers.newThread())
                //.onExceptionResumeNext(Observable.just(-1))
                .subscribe(new Subscriber<Integer>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Integer integer) {

                        System.out.println(integer);
                        try {
                            Thread.sleep(1000);
                        } catch (Exception e) {
                        }
                    }
                });
    }
}
